package com.longcom.ui;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.bairuitech.anychat.AnyChatBaseEvent;
import com.bairuitech.anychat.AnyChatCoreSDK;
import com.bairuitech.anychat.AnyChatDefine;
import com.bairuitech.anychat.AnyChatTextMsgEvent;
import com.longcom.domain.ConfigEntity;
import com.longcom.domain.User;
import com.longcom.service.ConfigService;
import com.longcom.util.HttpClientHelper;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity implements AnyChatBaseEvent,
		AnyChatTextMsgEvent
{
	public AnyChatCoreSDK anychat;
	private ConfigEntity configEntity;

	private String url;
	private ProgressDialog progressDialog;
	private ProgressDialog logoutDialog;
	private int userId = 0;

	private ArrayList<String> idList = new ArrayList<String>();
	private ArrayList<String> userList = new ArrayList<String>();
	private JSONArray users = new JSONArray();
	private ArrayList<User> userArray = new ArrayList<User>();
	private UserListAdapter userListAdapter;

	private ListView lv_users;
	private Button btn_refresh;
	private int remoteId = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		configEntity = ConfigService.LoadConfig(this);
		userListAdapter = new UserListAdapter();
		url = ((MyApplication) getApplication()).getServiceUrl();
		InitialSDK();

		progressDialog = ProgressDialog.show(this, "Login room", "wait...");
		progressDialog.setCancelable(true);
		configEntity = ConfigService.LoadConfig(this);
		anychat.SetBaseEvent(this);
		anychat.SetTextMessageEvent(this);
		ApplyVideoConfig();
		anychat.Connect(configEntity.ip, configEntity.port);

		initView();
	}
	
	@Override
	protected void onRestart()
	{
		// TODO Auto-generated method stub
		new QueryAllUserTask().execute();
		super.onRestart();
	}

	private void initView()
	{
		lv_users = (ListView) findViewById(R.id.lv_users);
		btn_refresh = (Button) findViewById(R.id.btn_refresh);
		lv_users.setAdapter(userListAdapter);
		lv_users.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3)
			{
				// TODO Auto-generated method stub
				anychat.SendTextMessage(Integer.valueOf(userArray.get(arg2).getUserId()), 1,
						"request for video");
				startVideoChat(userArray.get(arg2).getUserId());
			}
		});

	}

	private void sendMessage(String message)
	{
		anychat.SendTextMessage(-1, 0, message);
	}

	@Override
	protected void onResume()
	{
		// TODO Auto-generated method stub
		anychat.SetBaseEvent(this);
		idList.clear();
		userList.clear();
		int[] userID = anychat.GetOnlineUser();
		for (int i = 0; i < userID.length; i++)
		{
			idList.add("" + userID[i]);
		}
		for (int i = 0; i < userID.length; i++)
		{
			userList.add(anychat.GetUserName(userID[i]));
		}
		// new QueryAllUserTask().execute();
		userListAdapter.notifyDataSetChanged();
		super.onResume();
	}

	private void InitialSDK()
	{
		if (anychat == null)
		{
			anychat = new AnyChatCoreSDK();
			anychat.SetBaseEvent(this);
			if (configEntity.useARMv6Lib != 0)
				AnyChatCoreSDK.SetSDKOptionInt(
						AnyChatDefine.BRAC_SO_CORESDK_USEARMV6LIB, 1);
			anychat.InitSDK(android.os.Build.VERSION.SDK_INT, 0);
		}
	}

	@Override
	public void OnAnyChatConnectMessage(boolean bSuccess)
	{
		// TODO Auto-generated method stub
		if (bSuccess)
		{
			anychat.Login("android", "");
		} else
		{
			progressDialog.dismiss();
			Toast.makeText(getApplicationContext(), "connect server fail", 1)
					.show();
		}
	}

	@Override
	public void OnAnyChatLoginMessage(int dwUserId, int dwErrorCode)
	{
		System.out.println("userid=" + dwUserId + " errorcode=" + dwErrorCode);
		if (dwErrorCode == 0)
		{
			anychat.EnterRoom(1, "");
			userId = dwUserId;
		} else
		{
			progressDialog.dismiss();
			Toast.makeText(this, "登录失败，错误代码：" + dwErrorCode, Toast.LENGTH_SHORT)
					.show();
		}
	}

	@Override
	public void OnAnyChatEnterRoomMessage(int dwRoomId, int dwErrorCode)
	{
		// TODO Auto-generated method stub
		progressDialog.dismiss();
		if (dwErrorCode == 0)
		{
			Toast.makeText(getApplicationContext(), "entry room success", 1)
					.show();
			anychat.SetBaseEvent(this);
			idList.clear();
			userList.clear();
			int[] userID = anychat.GetOnlineUser();
			for (int i = 0; i < userID.length; i++)
			{
				idList.add("" + userID[i]);
			}
			for (int i = 0; i < userID.length; i++)
			{
				userList.add(anychat.GetUserName(userID[i]));
			}
			userListAdapter.notifyDataSetChanged();
			((MyApplication) getApplication()).setUserId(userId);
			int id = ((MyApplication) getApplication()).getId();
			UpdateIdTask task = new UpdateIdTask(id, userId);
			QueryAllUserTask allUserTask = new QueryAllUserTask();
			task.execute();
			allUserTask.execute();
		} else
		{
			Toast.makeText(getApplicationContext(), "entry room fail", 1)
					.show();
		}
	}

	@Override
	public void OnAnyChatOnlineUserMessage(int dwUserNum, int dwRoomId)
	{
		// TODO Auto-generated method stub

	}

	@Override
	public void OnAnyChatUserAtRoomMessage(int dwUserId, boolean bEnter)
	{
		// TODO Auto-generated method stub
		if (!bEnter)
		{
			for (int i = 0; i < userArray.size(); ++i)
			{
				if (String.valueOf(dwUserId).equals(
						userArray.get(i).getUserId()))
				{
					userArray.get(i).setUserId("0");
				}
			}
		}else
		{
			new QueryAllUserTask().execute();
		}

		/*
		 * if (bEnter) { idList.add("" + dwUserId);
		 * userList.add(anychat.GetUserName(dwUserId)); QueryAllUserTask task =
		 * new QueryAllUserTask(); task.execute();
		 * userListAdapter.notifyDataSetChanged(); } else { for (int i = 0; i <
		 * idList.size(); ++i) { if (idList.get(i).equals("" + dwUserId)) {
		 * idList.remove(i); userList.remove(i);
		 * userListAdapter.notifyDataSetChanged(); } } for(int i=0;
		 * i<userArray.size(); i++) { if(userArray.get(i).getUserId() ==
		 * String.valueOf(dwUserId)) { userArray.get(i).setUserId("0"); break; }
		 * }
		 */
		userListAdapter.notifyDataSetChanged();

	}

	@Override
	public void OnAnyChatLinkCloseMessage(int dwErrorCode)
	{
		// TODO Auto-generated method stub

	}

	/*
	 * update user's id that dispatcher from anychat server to local server
	 * return update row count from local database
	 */
	class UpdateIdTask extends AsyncTask<Void, Void, String>
	{
		private int id, userId;

		public UpdateIdTask(int id, int userId)
		{
			this.id = id;
			this.userId = userId;
		}

		@Override
		protected String doInBackground(Void... params)
		{
			List<NameValuePair> pairList = new ArrayList<NameValuePair>();
			NameValuePair idPair = new BasicNameValuePair("id", id + "");
			NameValuePair userIdPair = new BasicNameValuePair("userId", userId
					+ "");
			pairList.add(userIdPair);
			pairList.add(idPair);
			String result = HttpClientHelper.postData(url
					+ "ReportUserIdServlet", pairList);
			return result;
		}

		@Override
		protected void onPostExecute(String result)
		{
			System.out.println("row=" + result);
			if (Integer.valueOf(result.trim()) == 1)
			{
				Toast.makeText(getApplicationContext(),
						"upload user id success", 1).show();

			} else
			{
				Toast.makeText(getApplicationContext(), "upload fail", 1)
						.show();
			}
		}
	}

	class QueryAllUserTask extends AsyncTask<Void, Void, String>
	{

		@Override
		protected String doInBackground(Void... params)
		{
			// TODO Auto-generated method stub
			String result = HttpClientHelper.postData(url
					+ "QueryOnlineUserServlet", new ArrayList<NameValuePair>());
			return result;
		}

		@Override
		protected void onPostExecute(String result)
		{
			// TODO Auto-generated method stub
			System.out.println(result);
			try
			{
				users = new JSONArray(result);
				/*
				 * for(int i=0; i<users.length(); ++i) { JSONObject userItem =
				 * users.optJSONObject(i); int itemId =
				 * userItem.getInt("userId"); for(int j=0; j<idList.size(); ++j)
				 * { if(idList.get(j).equals(itemId+"")) { userList.set(j,
				 * userList.get(j)+":"+userItem.getString("username")); } } }
				 */
				userArray.clear();
				for (int i = 0; i < users.length(); i++)
				{
					JSONObject userItem = users.optJSONObject(i);
					if (userItem.getInt("id") == ((MyApplication) getApplication())
							.getId())
					{
						continue;
					}
					User user = new User();
					user.setId(userItem.getInt("id") + "");
					user.setUserId(userItem.getInt("userId") + "");
					user.setUsername(userItem.getString("username"));
					user.setPassword(userItem.getString("password"));
					// user.setRemark(userItem.getString("remark"));
					userArray.add(user);
				}

				userListAdapter.notifyDataSetChanged();
			} catch (JSONException e)
			{
				// TODO Auto-generated catch block
				Toast.makeText(getApplicationContext(), "query userlist fail",
						0).show();
				e.printStackTrace();
			}
			super.onPostExecute(result);
		}

	}

	@Override
	public void OnAnyChatTextMessage(int dwFromUserid, int dwToUserid,
			boolean bSecret, String message)
	{
		System.out.println(dwFromUserid + ":" + message);
		/*
		 * if (message.equals("hello")) { sendMessage("userId:" + userId);
		 * startVideoChat(dwFromUserid + ""); } if (message.contains("userId:"))
		 * { remoteId = Integer.valueOf(message.split(":")[1]);
		 * System.out.println("remote userId:" + remoteId);
		 * startVideoChat(remoteId + ""); }
		 */
		if (message.equals("request for video"))
		{
			startVideoChat(dwFromUserid + "");
		}
	}

	private void startVideoChat(String remoteId)
	{
		Intent intent = new Intent(MainActivity.this, VideoActivity.class);
		intent.putExtra("userId", remoteId);
		startActivity(intent);
	}

	class UserListAdapter extends BaseAdapter
	{
		private LayoutInflater inflater;

		public UserListAdapter()
		{
			super();
			this.inflater = LayoutInflater.from(MainActivity.this);
			// TODO Auto-generated constructor stub
		}

		@Override
		public int getCount()
		{
			// TODO Auto-generated method stub
			// return userList.size();
			return userArray.size();
		}

		@Override
		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			// return userList.get(position);
			return userArray.get(position);
		}

		@Override
		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			// TODO Auto-generated method stub

			/*
			 * TextView textView = new TextView(MainActivity.this);
			 * textView.setText(idList.get(position) + " : " +
			 * userList.get(position)); textView.setHeight(80);
			 * textView.setTextSize(22.0f);
			 * textView.setGravity(Gravity.CENTER_VERTICAL);
			 */

			ViewHolder holder = null;
			if (convertView == null)
			{
				holder = new ViewHolder();
				convertView = inflater.inflate(R.layout.item_user, null);
				holder.tv_id = (TextView) convertView.findViewById(R.id.tv_id);
				holder.tv_userid = (TextView) convertView
						.findViewById(R.id.tv_userid);
				holder.tv_username = (TextView) convertView
						.findViewById(R.id.tv_username);
				convertView.setTag(holder);
			} else
			{
				holder = (ViewHolder) convertView.getTag();
			}
			// holder.tv_id.setText(idList.get(position));
			// holder.tv_userid.setText(userList.get(position));
			holder.tv_id.setText(userArray.get(position).getId());
			holder.tv_userid.setText("0".equals(userArray.get(position)
					.getUserId().trim()) ? "offline" : "online");
			holder.tv_username.setText(userArray.get(position).getUsername());

			return convertView;
		}

	}

	class ViewHolder
	{
		public TextView tv_id;
		public TextView tv_userid;
		public TextView tv_username;
	}

	class LogoutTask extends AsyncTask<Void, Void, String>
	{
		@Override
		protected String doInBackground(Void... params)
		{
			// TODO Auto-generated method stub
			List<NameValuePair> pairList = new ArrayList<NameValuePair>();
			NameValuePair pair = new BasicNameValuePair("userId", userId + "");
			pairList.add(pair);
			String result = HttpClientHelper.postData(url + "LogoutServlet",
					pairList);
			return result;
		}

		@Override
		protected void onPostExecute(String result)
		{
			logoutDialog.dismiss();
			if (result != null)
			{
				int flag = -1;
				try
				{
					flag = Integer.valueOf(result.trim());
					if (flag == 1)
					{
						Toast.makeText(getApplicationContext(),
								"logout success", 1).show();
					}
				} catch (NumberFormatException e)
				{
					// TODO Auto-generated catch block
					Toast.makeText(getApplicationContext(), "logout error", 1)
							.show();
					e.printStackTrace();
				} finally
				{
					anychat.LeaveRoom(-1);
					anychat.Logout();
					finish();
				}

			} else
			{
				Toast.makeText(getApplicationContext(),
						"connect to server fail", 1).show();
				anychat.LeaveRoom(-1);
				anychat.Logout();
				finish();
			}

		}
	}

	private void ApplyVideoConfig()
	{
		ConfigEntity configEntity = ConfigService.LoadConfig(this);
		if (configEntity.configMode == 1) // 自定义视频参数配置
		{
			// 设置本地视频编码的码率（如果码率为0，则表示使用质量优先模式）
			AnyChatCoreSDK.SetSDKOptionInt(
					AnyChatDefine.BRAC_SO_LOCALVIDEO_BITRATECTRL,
					configEntity.videoBitrate);
			if (configEntity.videoBitrate == 0)
			{
				// 设置本地视频编码的质量
				AnyChatCoreSDK.SetSDKOptionInt(
						AnyChatDefine.BRAC_SO_LOCALVIDEO_QUALITYCTRL,
						configEntity.videoQuality);
			}
			// 设置本地视频编码的帧率
			AnyChatCoreSDK.SetSDKOptionInt(
					AnyChatDefine.BRAC_SO_LOCALVIDEO_FPSCTRL,
					configEntity.videoFps);
			// 设置本地视频编码的关键帧间隔
			AnyChatCoreSDK.SetSDKOptionInt(
					AnyChatDefine.BRAC_SO_LOCALVIDEO_GOPCTRL,
					configEntity.videoFps * 4);
			// 设置本地视频采集分辨率
			AnyChatCoreSDK.SetSDKOptionInt(
					AnyChatDefine.BRAC_SO_LOCALVIDEO_WIDTHCTRL,
					configEntity.resolution_width);
			AnyChatCoreSDK.SetSDKOptionInt(
					AnyChatDefine.BRAC_SO_LOCALVIDEO_HEIGHTCTRL,
					configEntity.resolution_height);
			// 设置视频编码预设参数（值越大，编码质量越高，占用CPU资源也会越高）
			AnyChatCoreSDK.SetSDKOptionInt(
					AnyChatDefine.BRAC_SO_LOCALVIDEO_PRESETCTRL,
					configEntity.videoPreset);
		}
		// 让视频参数生效
		AnyChatCoreSDK.SetSDKOptionInt(
				AnyChatDefine.BRAC_SO_LOCALVIDEO_APPLYPARAM,
				configEntity.configMode);
		// P2P设置
		AnyChatCoreSDK.SetSDKOptionInt(
				AnyChatDefine.BRAC_SO_NETWORK_P2PPOLITIC,
				configEntity.enableP2P);
		// 本地视频Overlay模式设置
		AnyChatCoreSDK.SetSDKOptionInt(
				AnyChatDefine.BRAC_SO_LOCALVIDEO_OVERLAY,
				configEntity.videoOverlay);
		// 回音消除设置
		AnyChatCoreSDK.SetSDKOptionInt(AnyChatDefine.BRAC_SO_AUDIO_ECHOCTRL,
				configEntity.enableAEC);
		// 平台硬件编码设置
		AnyChatCoreSDK.SetSDKOptionInt(
				AnyChatDefine.BRAC_SO_CORESDK_USEHWCODEC,
				configEntity.useHWCodec);
		// 视频旋转模式设置
		AnyChatCoreSDK.SetSDKOptionInt(
				AnyChatDefine.BRAC_SO_LOCALVIDEO_ROTATECTRL,
				configEntity.videorotatemode);
		// 视频平滑播放模式设置
		AnyChatCoreSDK.SetSDKOptionInt(
				AnyChatDefine.BRAC_SO_STREAM_SMOOTHPLAYMODE,
				configEntity.smoothPlayMode);
		// 视频采集驱动设置
		AnyChatCoreSDK.SetSDKOptionInt(
				AnyChatDefine.BRAC_SO_LOCALVIDEO_CAPDRIVER,
				configEntity.videoCapDriver);
		// 本地视频采集偏色修正设置
		AnyChatCoreSDK.SetSDKOptionInt(
				AnyChatDefine.BRAC_SO_LOCALVIDEO_FIXCOLORDEVIA,
				configEntity.fixcolordeviation);
		// 视频显示驱动设置
		AnyChatCoreSDK.SetSDKOptionInt(
				AnyChatDefine.BRAC_SO_VIDEOSHOW_DRIVERCTRL,
				configEntity.videoShowDriver);
		// 音频播放驱动设置
		AnyChatCoreSDK.SetSDKOptionInt(AnyChatDefine.BRAC_SO_AUDIO_PLAYDRVCTRL,
				configEntity.audioPlayDriver);
		// 音频采集驱动设置
		AnyChatCoreSDK.SetSDKOptionInt(
				AnyChatDefine.BRAC_SO_AUDIO_RECORDDRVCTRL,
				configEntity.audioRecordDriver);
		// 视频GPU渲染设置
		AnyChatCoreSDK.SetSDKOptionInt(
				AnyChatDefine.BRAC_SO_VIDEOSHOW_GPUDIRECTRENDER,
				configEntity.videoShowGPURender);
	}

	@Override
	public void onBackPressed()
	{
		System.out.println("onBackPressed");
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle("Quit?");
		builder.setNegativeButton("No", new DialogInterface.OnClickListener()
		{

			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				// TODO Auto-generated method stub

			}
		});
		builder.setPositiveButton("Yes", new DialogInterface.OnClickListener()
		{

			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				// TODO Auto-generated method stub
				logoutDialog = ProgressDialog.show(MainActivity.this, "logout",
						"wait");
				logoutDialog.setCancelable(true);
				new LogoutTask().execute();
			}
		});
		builder.create().show();
		// super.onBackPressed();
	}

}
